<template>
  <PageWrapper class="high-form" title="派工单">

    <CollapseContainer title="基础信息">
      <BasicForm @register="registerForm" ref="formRef">
        <template #contractRequirementList="{ model }">
          <BasicTable @register="registerTable1" :dataSource="model.contractRequirementList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate1"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions1(record)" />
              </template>
            </template>
          </BasicTable>
        </template>
        <template #extInfoList="{ model }">
          <BasicTable @register="registerTable2" :dataSource="model.extInfoList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate2"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions2(record)" />
              </template>
            </template>
          </BasicTable>
        </template>
      </BasicForm>
    </CollapseContainer>

    <CollapseContainer title="流程信息">
      <SelectApprover :id="id" :type="type" @success="getFlowData" />
    </CollapseContainer>
    <a-button type="primary" @click="handleSubmitForm" v-if="serverData.showCommit"> 提交 </a-button> <span> </span>
    <a-button type="primary" @click="handleSaveForm(0)" v-if="serverData.showCommit"> 存草稿 </a-button>
  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, computed, unref } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { Button, Tag, List, } from 'ant-design-vue';
import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem, } from '/@/components/Table';
import { PageWrapper } from '/@/components/Page';
import { cloneDeep } from 'lodash-es';

import { formSchema } from './data';
import { update } from '/@/api/project/delivery';
import { businessdata } from '/@/api/work/work';
import { getDepts as getAllDept } from '/@/api/org/dept';
import { getAllList } from '/@/api/privilege/account';
import SelectApprover from '/@/views/process/SelectApprover.vue';

export default defineComponent({
  components: {
    BasicTable, TableAction, BasicForm, CollapseContainer, PageWrapper, Button, Tag, ApiSelect, SelectApprover,
    List, ListItem: List.Item, ListItemMeta: List.Item.Meta,
  },
  emits: ['success', 'register'],
  setup() {
    //主表单begin
    const [registerForm, { setFieldsValue, updateSchema, validate, }] = useForm({
      schemas: formSchema,
      labelWidth: 100,
      showActionButtonGroup: false,
    });

    const id = ref(0);
    const type = ref('CheckDelivery');
    const serverDataType: any = { showApprove: false, aaList: [], ccList: [] }
    const serverData = ref(serverDataType);
    const router = useRouter();



    onBeforeMount(() => {
      // 获取路由参数
      const r = useRoute();
      let idStr = r.params.id
      if (typeof (idStr) == 'string') {
        id.value = parseInt(idStr, 10)
      } else {
        id.value = parseInt(idStr[0], 10)
      }
    })

    onMounted(() => {
      if (id.value > 0) {
        setFieldsValue(serverData)
        businessdata({ id: id.value, type: type.value, index: 0 }).then(res => {

          if (res.itemName == '职业卫生' || res.itemName == '验收') {
            res.serviceType = '按次'
            res.serviceFrequency = 1
            updateSchema({
              field: 'serviceType',
              componentProps: {
                disabled: true,
                defaultValue: '按次',
              },
            });
            updateSchema({
              field: 'serviceFrequency',
              componentProps: {
                disabled: true,
                defaultValue: 1,
              },
            });
          }

          setFieldsValue(res)
          console.log('获取【派工单】数据成功', res)

        })
      }
      //console.log(`1.父页面onMounted, 通过setFieldsValue表单赋值`, serverData.value)
    })
    // 从子页面获取表单数据
    function getFlowData(returnData: any) {
      serverData.value = returnData
    }


    //提交，需要选择审批人
    async function handleSubmitForm() {
      if (serverData.value.aaList == null || serverData.value.aaList.length == 0) {
        createMessage.success({
          content: '请选择审批人',
          duration: 1,
        });
        return
      }
      handleSaveForm(1).then(res => {
        console.log('保存成功', res)
        // 提交成功后跳转到已处理页面
        if (res) {
          router.push('/work/work-done');
        } else {
          createMessage.error({
            content: '提交失败，该业务合同收款低于合同登记中派工到账比例，审批人必须为总经办相关人员',
            duration: 1,
          });
          return;
        }

      });
    }
    //存草稿
    async function handleSaveForm(submit) {
      const values = await validate();
      let content = '存草稿成功'
      values['isCommit'] = false
      if (submit === 1) {
        content = '提交成功'
        values['isCommit'] = true
        values['aaList'] = serverData.value.aaList
        values['ccList'] = serverData.value.ccList
      }
      values.contractRequirementList = getDataSource1()
      values.extInfoList = getDataSource2()

      console.log('formData=', values)
      let result = await update(values)
      if (submit === 0) {
        createMessage.success({
          content: content,
          duration: 1,
        });
      }
      //刷新数据
      businessdata({ id: id.value, type: type.value, index: 0 }).then(res => {
        setFieldsValue(res)
        console.log('获取【派工单】数据成功', res)
      })

      return result;
    }
    function getStep(step: number) {
      router.push('/project/step' + step + '/' + id.value);
    }
    //主表单end

    //可编辑表格1begin
    const [registerTable1, { getDataSource: getDataSource1, insertTableDataRecord: insertTableDataRecord1, deleteTableDataRecord: deleteTableDataRecord1, }] = useTable({
      columns: [{
        title: '分包单位',
        dataIndex: 'type',
        editRow: true,
      }, {
        title: '金额(元)',
        dataIndex: 'amount',
        editRow: true,
      }, {
        title: '备注',
        dataIndex: 'remark',
        editRow: true,
      },],
      formConfig: {
        labelWidth: 120,
        showAdvancedButton: false,
        showResetButton: false,
        autoSubmitOnEnter: true,
      },
      canColDrag: true,
      useSearchForm: false,
      bordered: true,
      showIndexColumn: false,
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        fixed: false,
      },
    });
    //列表操作栏定义
    function createActions1(record: EditRecordRow): ActionItem[] {
      if (!record.editable) {
        return [
          {
            tooltip: '编辑',
            icon: 'clarity:note-edit-line',
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
            onClick: handleEdit1.bind(null, record),
          },
          {
            tooltip: '删除',
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete1.bind(null, record),
              placement: 'left'
            },
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave1.bind(null, record),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel1.bind(null, record),
          },
        },
      ];
    }

    function handleCreate1() {
      let item = { type: '', amount: 0, remark: '' }
      insertTableDataRecord1(item)
    }

    const currentEditKeyRef1 = ref('');

    function handleEdit1(record: EditRecordRow) {
      currentEditKeyRef1.value = record.key;
      record.onEdit?.(true);
    }

    function handleCancel1(record: EditRecordRow) {
      currentEditKeyRef1.value = '';
      record.onEdit?.(false, false);
    }

    function handleDelete1(record: EditRecordRow) {
      deleteTableDataRecord1(record.id)
    }

    async function handleSave1(record: EditRecordRow) {
      // 校验
      createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();
      if (valid) {
        try {
          const data = cloneDeep(record.editValueRefs);
          console.log(data);
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }
    //可编辑表格1end

    //可编辑表格2begin
    const [registerTable2, { getDataSource: getDataSource2, insertTableDataRecord: insertTableDataRecord2, deleteTableDataRecord: deleteTableDataRecord2, }] = useTable({
      columns: [{
        title: '部门',
        dataIndex: 'dept',
        editRow: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          api: getAllDept,
          showSearch: true,
          optionFilterProp: 'label',
          resultField: 'data',
          labelField: 'name',
          valueField: 'name',
        },
      }, {
        title: '人员',
        dataIndex: 'staff',
        editRow: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          disabled: true,
          api: getAllList,
          showSearch: true,
          optionFilterProp: 'label',
          params: {},
          labelField: 'realName',
          valueField: 'realName',
        }
      }, {
        title: '金额(元)',
        dataIndex: 'amount',
        editRow: true,
      },],
      formConfig: {
        labelWidth: 120,
        showAdvancedButton: false,
        showResetButton: false,
        autoSubmitOnEnter: true,
      },
      canColDrag: true,
      useSearchForm: false,
      bordered: true,
      showIndexColumn: false,
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        fixed: false,
      },
    });
    //列表操作栏定义
    function createActions2(record: EditRecordRow): ActionItem[] {
      if (!record.editable) {
        return [
          {
            tooltip: '编辑',
            icon: 'clarity:note-edit-line',
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
            onClick: handleEdit2.bind(null, record),
          },
          {
            tooltip: '删除',
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete2.bind(null, record),
              placement: 'left'
            },
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave2.bind(null, record),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel2.bind(null, record),
          },
        },
      ];
    }

    function handleCreate2() {
      let item = { dept: '', staff: '', amount: 0 }
      insertTableDataRecord2(item)
    }

    const currentEditKeyRef = ref('');

    function handleEdit2(record: EditRecordRow) {
      currentEditKeyRef.value = record.key;
      record.onEdit?.(true);
    }

    function handleCancel2(record: EditRecordRow) {
      currentEditKeyRef.value = '';
      record.onEdit?.(false, false);
    }

    function handleDelete2(record: EditRecordRow) {
      deleteTableDataRecord2(record.id)
    }

    const { createMessage } = useMessage();

    async function handleSave2(record: EditRecordRow) {
      // 校验
      createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();
      if (valid) {
        try {
          const data = cloneDeep(record.editValueRefs);
          console.log(data);
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }
    //可编辑表格2end

    return {     
      registerTable1, handleCreate1, handleEdit1, handleDelete1, handleSave1, createActions1,
      registerTable2, handleCreate2, handleEdit2, handleDelete2, handleSave2, createActions2,
      registerForm, handleSaveForm, handleSubmitForm,
      getFlowData, serverData, id, type, getStep,
    };
  },
});
</script>
